// @Desc:
// @CreateTime: 2020/10/8
package router

import (
	"net/http"
	"strings"

	"gitee.com/xuesongtao/gotool/xlog"
	"github.com/gin-gonic/gin"
	"mycrm.com/controller"
	"mycrm.com/controller/customer"
	"mycrm.com/controller/statistics"
	"mycrm.com/controller/user"
	"mycrm.com/controller/visit"
	"mycrm.com/controller/wx"
	"mycrm.com/utils"
)

func Routers(router *gin.Engine) {
	router.Use(authIsOkMiddle)
	router.POST("/mycrmapi/login", user.Login)
	router.POST("/mycrmapi/register", user.Register)
	router.GET("/mycrmapi/index/:uid/:roleId", statistics.Index)
	//  用户
	userRouters := router.Group("/mycrmapi/user")
	{
		userRouters.GET("/list", user.List)
		userRouters.GET("/getRoleInfo", user.GetRoleInfo)
		userRouters.POST("/add", user.Register)
		userRouters.POST("/edit", user.Edit)
		userRouters.POST("/del/:curUserId/:delUid", user.Del)
		userRouters.GET("/showMenu/:uid", user.ShowMenu)
		userRouters.GET("/getDesginer", user.GetDesginer)
		userRouters.GET("/getMenus/:roleId", user.GetMenus)

		// 分组
		userRouters.GET("/grouplist", user.GroupList)
		userRouters.POST("/addOrEditgroup/:action", user.AddOrEditGroup)
		userRouters.POST("/group/del/:groupId", user.DelGroup)
		userRouters.GET("/getGroupInfo", user.GetGroupInfo)

	}

	// 客户
	customerRouters := router.Group("/mycrmapi/customer")
	{
		customerRouters.GET("/list", customer.List)
		customerRouters.POST("/add", customer.Add)
		customerRouters.POST("/edit", customer.Edit)
		customerRouters.POST("/del/:uid/:delCustomerId", customer.Del)
	}

	// 回访列表
	visitRouters := router.Group("/mycrmapi/visit")
	{
		visitRouters.GET("/list", visit.List)
		visitRouters.POST("/callCustomer", visit.CallCustomer)
		visitRouters.GET("/getVisitRecord/:customerId/:isAll", visit.GetVisitRecord)
		// visitRouters.GET("/test", visit.StatisticsVisitByDay)
	}

	// 微信接口
	wxRouters := router.Group("/mycrmapi/wx")
	{
		wxRouters.GET("/xuesongtaotestGetAccessToken", wx.TestGetAccessToken)
		wxRouters.Any("/comeWxMsg", wx.ComeWxMsg)
	}

}

// 验证 login_code 是否正确
func authIsOkMiddle(c *gin.Context) {
	loginToken, _ := c.Cookie("token")
	curPath := c.Request.RequestURI
	xlog.Info("curPath: ", curPath)
	// 判断下是否从微信过来的, 微信过来的话就不用这样
	isComeWx := strings.Contains(curPath, "/wx")
	isTest := strings.Contains(curPath, "/xuesongtaotest")
	tokenIsOk, _ := utils.VerifyTokenIsOk(loginToken)
	if curPath == "/mycrmapi/login" || curPath == "/mycrmapi/register" {
		xlog.Info("visitPath: ", curPath)
	} else if tokenIsOk { // 判断 token 是否有效
		xlog.Info("visitPath: ", curPath)
	} else if isTest { // 测试接口v
		xlog.Info("this is test, url: ", curPath)
	} else if isComeWx { // 微信接口
		xlog.Info("come wx request!")
		// 验签
		ok := wx.CheckSignature(c)
		if !ok {
			c.AbortWithStatusJSON(http.StatusBadRequest, &controller.Response{
				Status: 0,
				Msg:    "you is not access visit",
			})
		}
	} else { // 其他
		c.AbortWithStatusJSON(http.StatusBadRequest, &controller.Response{
			Status: 0,
			Msg:    "you is not access visit",
		})
	}

}
